package com.example.deepschool.service.Course;

import com.example.deepschool.Model.Pagination;
import com.example.deepschool.Model.Response.ResponseData;
import com.example.deepschool.Model.User;
import com.example.deepschool.Model.UserCourse;
import com.example.deepschool.enums.GlobalVariables_String;
import com.example.deepschool.exception.CustomException;
import com.example.deepschool.repositories.CourseRepository;
import com.example.deepschool.repositories.UserCourseRepository;
import com.example.deepschool.util.*;
import lombok.SneakyThrows;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class CourseImpl implements Course {
	
	private final CourseRepository courseRepository;
	private final UserCourseRepository userCourseRepository;
	
	public CourseImpl (CourseRepository courseRepository,
	                   UserCourseRepository userCourseRepository) {
		this.courseRepository = courseRepository;
		this.userCourseRepository = userCourseRepository;
	}
	
	
	private com.example.deepschool.Model.Course getCourse (com.example.deepschool.Model.Course course) {
		try{
			if( this.courseRepository.update(course)>0){
				return course;
			}
			throw new PersistenceException("课程信息更新失败");
		} catch (Exception e){
			throw new RuntimeException("服务器异常");
		}
	}
	
	@SneakyThrows
	@Override
	public void addCourse (com.example.deepschool.Model.Course course, String UUID) {
		try {
			User user = User.fromJson( Redis.HGET( Redis.GET( UUID ), "user" ) );
			if ( ! PermissionsControl.VERIFY_PUBLISH_COURSE( user.getPermissions( ) ) ) {
				throw new RuntimeException( "没有权限." );
			}
			this.courseRepository.insert( course );
			UserCourse userCourse = new UserCourse( user.getId( ), course.getId( ) );
			this.userCourseRepository.insert( userCourse );
			
		} catch ( Exception e ) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}

	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Course update (com.example.deepschool.Model.Course course, String UUID) {
		try{
			User user = User.fromJson(Redis.HGET(Redis.GET(UUID),"user"));
			if(! PermissionsControl.VERIFY_MODIFY_OWN_COURSE(user.getPermissions())){
				throw new RuntimeException("没有权限.");
			}
			Long[] userIds = this.userCourseRepository.selectUserIds( course.getId() );
			boolean isCourseMaster = false;
			for ( Long userId : userIds ) {
				if ( userId.equals( user.getId( ) ) ) {
					isCourseMaster = true;
					break;
				}
			}
			if ( ! isCourseMaster ) {
				throw new RuntimeException( "你不属于该课程的管理者" );
			}
			com.example.deepschool.Model.Course oldcourse = this.courseRepository.select(course.getId());
			if( oldcourse == null){
				throw new RuntimeException("课程不存在");
			}
			course.setCoverImage(oldcourse.getCoverImage());
			return getCourse(course);
		} catch (Exception e){
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException( 400, e.getMessage( ) );
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Course putCoverImage (MultipartFile file, String fileSHA256, String courseId, String UUID) {
		String Path = null;
		boolean isDelPath = false;
		try {
			User user = User.fromJson( Redis.HGET( Redis.GET( UUID ), "user" ) );
			if ( ! PermissionsControl.VERIFY_MODIFY_OWN_COURSE( user.getPermissions( ) ) ) {
				throw new RuntimeException( "没有权限." );
			}
			Long[] userIds = this.userCourseRepository.selectUserIds( Long.parseLong( courseId ) );
			boolean isCourseMaster = false;
			for ( Long userId : userIds ) {
				if ( userId.equals( user.getId( ) ) ) {
					isCourseMaster = true;
					break;
				}
			}
			if ( ! isCourseMaster ) {
				throw new RuntimeException( "你不属于该课程的管理者" );
			}
			com.example.deepschool.Model.Course course = this.courseRepository.select(Long.parseLong(courseId));
			if ( course == null ) {
				throw new RuntimeException( "课程不存在." );
			}
			String oldCourseImage = course.getCoverImage();
			String type = IO.getFileType( file );
			if ( ! Verify.VerifyFileType_Image( type ) ) {
				throw new RuntimeException( "文件类型，不允许作为课程封面" );
			}
			String SHA_256 = SHA256.calculateFileSHA256( file );
			if ( ! SHA_256.equals( fileSHA256 ) ) {
				throw new RuntimeException( "文件在传输的过程中存在异常" );
			}
			Path = GlobalVariables_String.File_Path_CourseImage.getValue() + SHA_256;
			String oldPath = GlobalVariables_String.File_Path_CourseImage.getValue() + oldCourseImage;
			if ( ! IO.isFileExist( Path ) ) {
				IO.writeFile( file, Path );
			}
			if( this.courseRepository.selectCoverImageCount( oldCourseImage ) == 1 ){
				IO.deleteFile(oldPath);
			}
			if( this.courseRepository.selectCoverImageCount(SHA_256) ==0 ){
				isDelPath = true;
			}
			course.setCoverImage(SHA_256);
			return getCourse(course);
		} catch ( Exception e ) {
			if(isDelPath){
				IO.deleteFile(Path);
			}
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException( 400, e.getMessage( ) );
		}
	}

	@SneakyThrows
	@Override
	public ResponseData getCourseImage (String CourseImage, String range) {
		try{
			long start = 0;
			if (range != null) {
				start = Long.parseLong(range.split("=")[1].split("-")[0]);
			}
			CourseImage = ! CourseImage.isEmpty() ? CourseImage : GlobalVariables_String.CourseImage_Default.getValue();
			String path = GlobalVariables_String.File_Path_CourseImage.getValue() + CourseImage;
			return IO.onlineReadFile(path, start, range);
		}catch ( RuntimeException e ) {
			throw new CustomException( 400, e.getMessage( ) );
		}


	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Course[] getCourseByPagination (Integer Page, Integer limit) {
		try {
			Pagination pagination = new Pagination();
			if (limit == null) {
				pagination.page(Page);
			} else {
				pagination.page(Page, limit);
			}
			return this.courseRepository.selectByPagination(pagination);
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Course[] getCourseByName (String name) {
		try {
			return this.courseRepository.selectByName(name);
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Course[] getCourseByUserId (String UUID) {
		try {
			User user = User.fromJson(Redis.HGET(Redis.GET(UUID), "user"));
			Long[] courseIds = this.userCourseRepository.selectCourseIds(user.getId());
			if (courseIds.length == 0) {
				return new com.example.deepschool.Model.Course[0];
			}
			return this.courseRepository.selectByIds(courseIds);
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.Course getCourse (Long courseId) {
		try {
			return this.courseRepository.select(courseId);
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
	
	
}